import json
import xmltodict
from collections import OrderedDict

def xmltojson(xmlpath, jsonpath):  
    """input xmlpath and jsonpath make xml to json"""
    file_object = open(xmlpath, encoding='utf-8')
    try:
        all_the_xmlStr = file_object.read()
    finally:
        file_object.close()
    # xml To dict
    convertedDict = xmltodict.parse(all_the_xmlStr)  
    # ensure_ascii 设置为False 中文可以转换
    jsonStr = json.dumps(convertedDict, ensure_ascii=False, indent=4)  
    # 写入文件 写入为utf-8编码
    with open(jsonpath, 'w', encoding='utf-8') as f:
    # 除去xmltodict 转换时默认添加的'@' 符号
        # f.write(jsonStr.replace('@', ''))
        f.write(jsonStr)


def jsontoxml(jsonpath, xmlpath):
    """input jsonpath and xmlpath make json to xml"""
    file_object = open(jsonpath, encoding='utf-8')
    try:
        all_the_jsonStr = file_object.read()
    finally:
        file_object.close()
    # loads的时候指定函数处理，object_pairs_hook=OrderedDict，否则会排序错乱
    convertedJson = xmltodict.unparse(json.loads(all_the_jsonStr, object_pairs_hook=OrderedDict), pretty=True)
    with open(xmlpath, 'w', encoding='utf-8') as j:
        j.write(convertedJson)


if __name__ == '__main__':
    # xmltojson(r'F:\chen\pythonworkspace\PythonGithub\TestFile\EMR-PL-01新增个人身份注册-F.xml', r'F:\chen\pythonworkspace\PythonGithub\TestFile\EMR-PL-01新增个人身份注册-F.json')
    jsontoxml(r'F:\chen\pythonworkspace\PythonGithub\TestFile\EMR-PL-01新增个人身份注册-F.json', r'F:\chen\pythonworkspace\PythonGithub\TestFile\EMR-PL-01新增个人身份注册-F-new.xml')
